# Users controller controls leaderboards and hide actions
# In 13wins, the leaderboard displays global/friend rankings based on a variety of player stats
# In 13wins, the user may hide notifications and messages

class UsersController < ApplicationController

  # List users based on leaderboard filter requirements
  def index

    #Add user invite WinPoint 
     i = 0
    if ids = params[:ids]
    users = facebook_session.users(ids,[:name])
    ids.each_with_index do |id,index|
      unless PointHistory.find(:first,:conditions=>["user_id =? and action='Invite " + users[index].name + " to 13wins.' and related_user_id=?",current_user.id,id])
        PointHistory.create(:user_id=>current_user.id,:action=>'Invite ' + users[index].name + ' to 13wins.',:point=>PointConfig.find_by_name("invite_sent").point,:earning => true,:related_user_id=>id)
        i = i + 1
      end
    end
    current_user.point = current_user.point + i*PointConfig.find_by_name("invite_sent").point
    current_user.invitation_sent_number = current_user.invitation_sent_number.to_i + i
    current_user.save
    flash[:notice] = i.to_s + " invitations sent. You earn #{i*50} WinPoints!!"
   # Redirect_to "http://apps.facebook.com/" + @app_name + "/buy_wins?sent_count=" + i if session[:notice]
    end

    @filter = params[:filter] || "most_popular"
    case @filter
    when "current"
      # @winstreaks = Winstreak.scoped(:include=>:user,:order=>"#{User.table_name}.win_percentage DESC")
      @users = User.scoped(:include=>:winstreak,:order=>"#{Winstreak.table_name}.streak_count DESC")
      # @winstreaks = @users.collect &:winstreak
      @action = "current_streak"
    when "total_bets"
      @users = User.scoped(:order=>"#{User.table_name}.bets_count DESC")
      @action = "bets"
    when "percentage"
      @users = User.scoped(:order=>"#{User.table_name}.win_percentage DESC", :condition => "#{User.table_name}.bets_count > 9") 
	  @action = "users_win_percentage"
    when "all"
      # Best streak
      @winstreaks = Winstreak.scoped(:order=>"streak_count DESC")
      @streak_name = "Best Streak"
    when "recent_winner"
      # @bets = Bet.scoped(:conditions=>{:win=>true},:group=>"#{Bet.table_name}.user_id",:order=>"#{Bet.table_name}.updated_at")
      @winstreaks = Winstreak.scoped(:conditions=>{:got_prize=>true})
      @action = "recent_winners"
    when "most_popular"
      @users = User.scoped(
        :order=>"score DESC"
      )
      @action = "most_popular"
    else
      @winstreaks = Winstreak.scoped(:order=>"streak_count DESC")
    end

    common_scope  = {:limit=>20}
    friends_scope = {:conditions=>["user_id in (?)",current_user.friend_ids.push(current_user.id)]}
    case params[:type]
    when "friends","",nil
      @winstreaks = @winstreaks.scoped(friends_scope.merge(:group=>"#{Winstreak.table_name}.user_id")) if @winstreaks
      @users      = @users.scoped(:conditions=>["#{User.table_name}.id in (?)",current_user.friend_ids.push(current_user.id)]) if @users
      @bets       = @bets.scoped(friends_scope) if @bets
    when "global"
      # default scope was global
    end
    @winstreaks = @winstreaks.all common_scope.merge(:select=>"*,max(streak_count) AS streak_count",:group=>"#{Winstreak.table_name}.user_id") if @winstreaks
    @users      = @users.all common_scope if @users
    @bets       = @bets.all common_scope if @bets
    logger.debug "action: #{@action}"
    if params[:auth_token]
      redirect_to "http://apps.facebook.com/" + FB_NAME 
    else
      render :action=>@action if @action
    end
  end


  # Hide bookmark box action 
  def hide_bookmark
    logger.error "----------------------------------"
    logger.error params[:id]
    logger.error "----------------------------------"
    user = User.find(params[:id])
    user.hide_bookmark = true
    user.save
    render :nothing=>true
  end

  # Hide instructions action 
  def hide_howto
    logger.error "---------------hide_howto-------------------"

    user = User.find(params[:id])
    user.hide_howto = true
    user.save
    render :nothing=>true
  end

  # Action to hide challenge 
  def hide_ch
    ch = Challenge.find(params[:id])
    ch.hide = true
    ch.save
    render :nothing=>true
  end

  # Action to hide challenge from_user 
  def hide_ch_from_user
    ch = Challenge.find(params[:id])
    ch.hide_from_user = true
    ch.save
    render :nothing=>true
  end

  # Action to hide challenge to_user 
  def hide_ch_to_user
    ch = Challenge.find(params[:id])
    ch.hide_to_user = true
    ch.save
    render :nothing=>true
  end
  
  # Action to hide challenge result from_user 
  def hide_ch_from_user_result
    ch = Challenge.find(params[:id])
    ch.hide_from_user_result = true
    ch.save
    render :nothing=>true
  end
  
  # Action to hide challenge result to_user   
  def hide_ch_to_user_result
    ch = Challenge.find(params[:id])
    ch.hide_to_user_result = true
    ch.save
    render :nothing=>true
  end


  # Show user info
  def show
  end
  
  # Invitation sent action
  def invited
    i = 0
    ids = params[:ids]
    ids.each do |id| 
      unless PointHistory.find(:first,:conditions=>["user_id =? and action='invite friend' and related_user_id=?",current_user.id,id])
        PointHistory.create(:user_id=>current_user.id,:action=>'invite friend',:point=>PointConfig.find_by_name("invite_sent").point,:earning => true,:related_user_id=>id)
        i = i + 1
      end
    end
    current_user.point = current_user.point + i*PointConfig.find_by_name("invite_sent").point
    current_user.save
    flash[:notice] = "You earned #{i*PointConfig.find_by_name("invite_sent").point} WinPoints via your invite request(s)."
    redirect_to buy_wins_path
  end

  # Refresh profile action 
  def refresh_profile
    @user = User.find params[:id]
    WinstreakPublisher.deliver_update_profile(@user)
    flash[:notice] = "Profile refreshed."
    redirect_to bets_path
  end

end
